﻿using System;
using System.Configuration;
using System.Web;
using System.IO;

namespace Shuba.Web.master
{
    public partial class branch_nip_so_upload : basePage
    {
        string msg;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_BRANCH_NIP_SO_MAP");

                if (!IsUserAdd(acl))
                {
                    msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_NIP_SO_MAP");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Boolean fileOK = false;
                String path = Server.MapPath("~/uploads/");
                string ErrMessage = "";
                int ErrLine = 0;

                if (FileUpload1.HasFile)
                {
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = { ".txt", ".csv" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;

                    string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(fName);

                    var filestream = File.OpenText(fName);
                    string contents = filestream.ReadToEnd();
                    filestream.Close();

                    var bll = new Business.BranchNipSOMap();
                    Model.BranchNipSOMapInfo Info;
                    Shuba.Business.MsStd _MstStd = new Shuba.Business.MsStd();
                    Shuba.Model.MstStdInfo mstInfo = new Shuba.Model.MstStdInfo();

                    Shuba.Business.User _User = new Shuba.Business.User();
                    string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];
                    string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];

                    string CurNIP;

                    char rowDelimiter = '\n';
                    char fldDelimiter = '\t';

                    var rows = contents.Split(rowDelimiter);

                    try
                    {
                        for (var i = 1; i < rows.Length; i++)
                        {
                            var fields = rows[i].Split(fldDelimiter);

                            if (fields.Length > 1)
                            {
                                try
                                {
                                    if (_User.GetAllUser(fields[2].Trim()).Name == null)
                                    {
                                        ErrMessage += "<BR> Invalid NIP at Column : 3, Line :" + i.ToString() + ", Please make sure NIP is correct and already registered in Console Management"; //this.GetGlobalResourceObject("Messages", "AppCodeExist").ToString();
                                    }

                                    if (fields[3].Trim() == string.Empty) ErrMessage += "<BR> User Type is Required at Column : 4, Line :" + i.ToString();

                                    if (fields[3].Trim() == "UM" && bll.GetUMByUnit(fields[0].Trim()).NIP != null)
                                    {
                                        ErrMessage += "<BR> Invalid Data, UM is already registered in Unit [" + fields[0].Trim() + "], Please check Column : 1 and 4, Line :" + i.ToString(); ;
                                    }

                                    mstInfo = _MstStd.Get(fields[3].Trim(), Int16.Parse(ddlAppType.SelectedValue));
                                    if (mstInfo.MstType.Trim() == "P")
                                    {
                                        Shuba.Business.HO ho = new Shuba.Business.HO();
                                        if (ho.Get(fields[0].Trim()).HO_ID == null)
                                        {
                                            ErrMessage += "<BR> Invalid Unit Code at Column : 1, Line :" + i.ToString();
                                        }
                                    }

                                    if (mstInfo.MstType.Trim() == "R")
                                    {
                                        Shuba.Business.Regional ho = new Shuba.Business.Regional();
                                        if (ho.Get(fields[0].Trim()).RegionalID == null)
                                        {
                                            ErrMessage += "<BR> Invalid Unit Code at Column : 1, Line :" + i.ToString();
                                        }
                                    }

                                    if (mstInfo.MstType.Trim() == "C")
                                    {
                                        Shuba.Business.Cluster ho = new Shuba.Business.Cluster();
                                        if (ho.Get(fields[0].Trim()).ClusterID == null)
                                        {
                                            ErrMessage += "<BR> Invalid Unit Code at Column : 1, Line :" + i.ToString();
                                        }
                                    }

                                    if (mstInfo.MstType.Trim() == "U")
                                    {
                                        Shuba.Business.Branch ho = new Shuba.Business.Branch();
                                        if (ho.Get(fields[0].Trim()).BranchID == null)
                                        {
                                            ErrMessage += "<BR> Invalid Unit Code at Column : 1, Line :" + i.ToString();
                                        }
                                    }

                                    if (!IsValidEntryFormat(fields[4].Trim(), "NS")) ErrMessage += "<BR> Invalid Phone Number Value or Format at Column : 5, Line :" + i.ToString();

                                    if (fields[1].Trim() != string.Empty && fields[3].Trim() == "SO")
                                    {
                                        CurNIP = bll.GetByAOCode(fields[1].Trim(), SPADAAppCode).NIP + "";
                                        if (CurNIP != "" && CurNIP.Trim() != fields[2].Trim())
                                        {
                                            ErrMessage += "<BR> Invalid AO Code, AO Code is already registered in Database at Column :2, Line :" + i.ToString();
                                        }
                                    }

                                    if (fields[3].Trim() == "SO" && fields[5].Trim() == string.Empty) ErrMessage += "<BR> MAC Address is Required at Column : 6, Line :" + i.ToString();

                                }
                                catch (Exception ex)
                                {
                                    ErrMessage = ex.Message;
                                    lblStatus.Text = "<BR>Invalid Data Format, at line :" + i.ToString() + "<br>" + ErrMessage;
                                }

                                if (ErrMessage == "")
                                {
                                    Info = new Model.BranchNipSOMapInfo();

                                    try
                                    {
                                        Info.BRANCH_ID = fields[0].Trim();
                                        Info.AO_CODE = fields[1].Trim() == string.Empty ? "-" : fields[1].Trim();
                                        Info.NIP = fields[2].Trim();
                                        Info.USER_TYPE = fields[3].Trim();
                                        Info.HP = fields[4].Trim();
                                        Info.MAC_ADDRESS = fields.Length < 7 ? "" : fields[5].Trim();
                                        Info.AO_TYPE = fields.Length < 7 ? "" : fields[6].Trim();
                                        Info.ACT_TYPE = "UPLOAD";
                                        Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                        Info.ENTRY_DATE = ProcessingDate();
                                        Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                        Info.UPDATE_DATE = ProcessingDate();

                                        bll.Save(Info);
                                    }
                                    catch (Exception ex)
                                    {
                                        ErrMessage += ex.Message;
                                    }
                                }
                                else
                                {
                                    ErrLine = i;
                                    i = rows.Length;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage += "<br>" + GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        ErrMessage += "<br>" + ex.Message + "<br>Please check your data, and put \"space\" in HP column at Row 1";
                    }

                    File.Delete(fName);
                    AddLog("UPLOAD", "UPLOAD BRANCH NIP SO MAPPING");

                    if (ErrMessage == "")
                    {
                        msg = GetGlobalResourceObject("Messages", "UploadSuccessAlert").ToString();
                        lblStatus.Text = msg;
                        FileUpLoadValidator.Visible = false;
                        AlertAndRedirect(msg, "branch_nip_so_list.aspx");
                    }
                    else
                    {
                        ErrMessage += "<br>" + GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                        FileUpLoadValidator.Visible = false;
                    }
                }
                else
                {
                    msg = GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                    lblStatus.Text = msg;
                }
            }
        }

        //private string Validation()
        //{

        //}

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("branch_nip_so_list.aspx");
        }
    }
}
